package com.union.wx.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.union.wx.SNSUserInfo;
import com.union.wx.ShareUtil;
import com.union.wx.WeiXinUtil;
import com.union.wx.WeixinOauth2Token;


@Controller
@RequestMapping("/weixin")
public class WeiXinController{
	

    //微信获取用户信息
    @RequestMapping(value = "/wx")
    public String WeiXinTest(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	
    	SNSUserInfo snsUserInfo = (SNSUserInfo) request.getSession().getAttribute("snsUserInfo");
    	if(snsUserInfo != null){
    		 return "index";
    	}else{
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            String code = request.getParameter("code");
            // 通过code获取access_token
            WeixinOauth2Token oauth2Token =WeiXinUtil.getOauth2AccessToken(WeiXinUtil.appid, WeiXinUtil.appSecret, code);
            System.out.println(oauth2Token.toString());
            String accessToken=oauth2Token.getAccessToken();
            String openId=oauth2Token.getOpenId();
            //获取到用户的基本信息
            snsUserInfo = WeiXinUtil.getSNSUserInfo(accessToken, openId);
            if(snsUserInfo!=null){
            	request.getSession().setAttribute("snsUserInfo", snsUserInfo);
            }
            
            return "index";
    	}
    }
    
    @RequestMapping(value = "/getSignature", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getSignature(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> map = new HashMap<String, Object>();
		// 获取前台传来的三个参数
		String timestamp = request.getParameter("timestamp");
		String nonce_str = request.getParameter("nonce_str");
		String url = request.getParameter("url");

		// 获取token
		String accessToken = ShareUtil.getToken(WeiXinUtil.appid, WeiXinUtil.appSecret);

		// 获取ticket
		String ticket = ShareUtil.getTicket(accessToken); 

		// 获取签名
		String signature = ShareUtil.getSignature(ticket, url, nonce_str,timestamp); 

		map.put("nonceStr", nonce_str);
		map.put("timestamp", timestamp);
		map.put("signature", signature);

		return map;
    }
}
